// import dayjs from "dayjs";
import { type Ref, h, ref, reactive, computed, toRaw, onMounted } from "vue";
// import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import type { PaginationProps } from "@pureadmin/table";
/** 新增按钮 */
import { addDialog } from "@/components/ReDialog";
/** 新增/修改表单 */
import editForm from "../form/index.vue";
/** 新增表单数据类型 */
import type { FormItemProps } from "./types";
import {
  getRewardList,
  getShippingID,
  createReward,
  deleteReward,
  updateReward
} from "@/api/reward";
import { deviceDetection, getKeyList } from "@pureadmin/utils";
export function useManage(tableRef?: Ref) {
  // ⚙️状态初始化
  const formRef = ref();
  /** 重置密码 */
  /** 是否处于 Loding 状态 */
  const loading = ref(true);
  /** 账号是否启用 */
  const switchLoadMap = ref({});

  /** 表格数据 */
  const dataList = ref([]);

  /** shoppingid list */
  const shoppingidList = ref([]);
  /** 发货方法下拉菜单 */
  async function getDropdown() {
    const { data } = await getShippingID();
    console.log(data);
    shoppingidList.value = data;
  }

  /** 定义表头 */
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "礼品编号",
      prop: "goodsid",
      width: 130
    },
    {
      label: "图片",
      prop: "photo",
      minWidth: 130,
      cellRenderer: ({ row }) => (
        <el-image
          fit="cover"
          preview-teleported={true}
          src={row.photo}
          preview-src-list={Array.of(row.photo)}
          class="w-[50px] h-[50px] rounded-full align-middle"
        />
      )
    },
    {
      label: "名称",
      prop: "name",
      minWidth: 130
    },
    {
      label: "描述",
      prop: "desc",
      minWidth: 130
    },
    {
      label: "库存",
      prop: "inventory",
      minWidth: 130
    },
    {
      label: "发货方式",
      prop: "shipping",
      minWidth: 130,
      cellRenderer: ({ row }) => <span>{row.shipping.name}</span>
    },
    // {
    //   label: "状态",
    //   prop: "enable",
    //   minWidth: 90,
    //   cellRenderer: scope => (
    //     <el-switch
    //       size={scope.props.size === "small" ? "small" : "default"}
    //       loading={switchLoadMap.value[scope.index]?.loading}
    //       v-model={scope.row.enable}
    //       active-value={true}
    //       inactive-value={false}
    //       active-text="已上架"
    //       inactive-text="已下架"
    //       inline-prompt
    //       style={switchStyle.value}
    //       onChange={() => onChange(scope as any)}
    //     />
    //   )
    // },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  /** 多选数量 */
  const selectedNum = ref(0);
  /** 搜索用户表单 */
  const manageSearch = reactive({
    key: "",
    /** 发货方式 */
    shippingid: "",
    status: ""
  });
  /** 翻页器定义 */
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const switchStyle = computed(() => {
    return {
      "--el-switch-on-color": "#6abe39",
      "--el-switch-off-color": "#e84749"
    };
  });

  // 💡方法区
  /** 重置表单 */
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  /** 默认搜索方法 */
  async function onSearch() {
    console.log("触发搜索方法");
    loading.value = true;
    // const { data } = await getUserList(toRaw(form));
    const { data } = await getRewardList(toRaw(manageSearch));
    console.log(data);
    // console.log(result);
    dataList.value = data;
    // pagination.total = result.total;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }
  /** 切换按钮方法 */
  // function onChange({ row, index }) {
  //   ElMessageBox.confirm(
  //     `确认要<strong>${
  //       row.enable === false ? "停用" : "启用"
  //     }</strong><strong style='color:var(--el-color-primary)'>${
  //       row.username
  //     }</strong>用户吗?`,
  //     "系统提示",
  //     {
  //       confirmButtonText: "确定",
  //       cancelButtonText: "取消",
  //       type: "warning",
  //       dangerouslyUseHTMLString: true,
  //       draggable: true
  //     }
  //   )
  //     /** 确认操作 */
  //     .then(() => {
  //       switchLoadMap.value[index] = Object.assign(
  //         {},
  //         switchLoadMap.value[index],
  //         {
  //           loading: true
  //         }
  //       );
  //       setTimeout(() => {
  //         switchLoadMap.value[index] = Object.assign(
  //           {},
  //           switchLoadMap.value[index],
  //           {
  //             loading: false
  //           }
  //         );
  //         console.log(row.enable);
  //         let tips = row.enable === true ? "启用" : "停用";
  //         message(`已修改用户状态为: ${tips}`, {
  //           type: "success"
  //         });
  //       }, 300);
  //     })
  //     /** 取消操作 */
  //     .catch(() => {
  //       row.enable === true ? (row.enable = false) : (row.enable = true);
  //       message("操作取消", {
  //         type: "warning"
  //       });
  //     });
  // }
  /** 取消批量删除选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }
  /** 批量删除用户方法
   *当CheckBox选择项发生变化时会触发该事件
   */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    deleteReward(getKeyList(curSelected, "goodsid")).then(() => {
      // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
      message(`已删除用户编号为 ${getKeyList(curSelected, "goodsid")} 的数据`, {
        type: "success"
      });
      tableRef.value.getTableRef().clearSelection();
      onSearch();
    });
  }
  /** 新增礼品 */
  function openDialog(title = "新增", row?: FormItemProps) {
    if (title == "新增") {
      addDialog({
        title: `${title}礼品`,
        props: {
          formInline: {
            title,
            name: row?.name ?? "",
            desc: row?.desc ?? "",
            point: row?.point ?? 1,
            photo: row?.photo ?? "",
            imgid: row?.imgid ?? "",
            inventory: row?.inventory ?? 1
            // enable: row?.enable ?? true
          }
        },
        width: "46%",
        draggable: true,
        fullscreen: deviceDetection(),
        fullscreenIcon: true,
        closeOnClickModal: false,
        contentRenderer: () => h(editForm, { ref: formRef }),
        beforeSure: (done, { options }) => {
          const FormRef = formRef.value.getRef();
          const curData = options.props.formInline as FormItemProps;
          function chores() {
            message(`您${title}了名称为${curData.name}的这条数据`, {
              type: "success"
            });
            done(); // 关闭弹框
            onSearch(); // 刷新表格数据
          }
          FormRef.validate(valid => {
            if (valid) {
              // 表单规则校验通过
              console.log("curData", curData);
              // 实际开发先调用新增接口，再进行下面操作
              formRef.value.uploadPic();
              setTimeout(() => {
                createReward(curData);
                chores();
              }, 800);
            }
          });
        }
      });
    }
    if (title == "修改") {
      addDialog({
        title: `${title}礼品`,
        props: {
          formInline: {
            title,
            goodsid: row?.goodsid ?? "",
            name: row?.name ?? "",
            desc: row?.desc ?? "",
            point: row?.point ?? 1,
            photo: row?.photo ?? "",
            imgid: row?.imgid ?? "",
            inventory: row?.inventory ?? 1,
            shippingid: row.shipping?.shippingid ?? ""
          }
        },
        width: "46%",
        draggable: true,
        fullscreen: deviceDetection(),
        fullscreenIcon: true,
        closeOnClickModal: false,
        contentRenderer: () => h(editForm, { ref: formRef }),
        beforeSure: (done, { options }) => {
          const FormRef = formRef.value.getRef();
          const curData = options.props.formInline as FormItemProps;
          function chores() {
            message(`您${title}了名称为${curData.name}的这条数据`, {
              type: "success"
            });
            done(); // 关闭弹框
            onSearch(); // 刷新表格数据
          }
          // 判断是否上传图片
          FormRef.validate(valid => {
            if (valid) {
              // 表单规则校验通过
              if (curData.isUpload == 1) {
                formRef.value.uploadPic();
                setTimeout(() => {
                  updateReward(curData);
                  chores();
                }, 800);
              } else {
                updateReward(curData);
                chores();
              }
            }
          });
        }
      });
    }
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }
  /** 删除单个用户方法 */
  function handleDelete(row) {
    deleteReward([row.goodsid]).then(() => {
      message(`您删除了用户编号为${row.goodsid}的这条数据`, {
        type: "success"
      });
      onSearch();
    });
  }
  /** 修改单个用户方法 */
  function handleUpdate(row) {
    console.log(row);
  }
  /** 重置密码 */
  function handleReset(row) {
    console.log(row);
  }
  /** 翻页器-改变页大小 */
  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    console.log(`${val} items per page`);
  }
  /** 翻页器-改变页数 */
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    console.log(`current page: ${val}`);
  }
  /** 页面挂载钩子 */
  onMounted(async () => {
    onSearch();
    getDropdown();
  });

  return {
    formRef,
    loading,
    switchLoadMap,
    dataList,
    shoppingidList,
    columns,
    manageSearch,
    switchStyle,
    selectedNum,
    pagination,
    resetForm,
    onSearch,
    openDialog,
    onSelectionCancel,
    onbatchDel,
    handleSelectionChange,
    handleDelete,
    handleUpdate,
    handleReset,
    handleSizeChange,
    handleCurrentChange
  };
}
